package com.spotme
{
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.soap.WebService;
	
	public class SpotmeLocations
	{
		protected var _ip:String;
		protected var _username:String;
		protected var _password:String;
		protected var _token:String;
		protected var _ws:WebService;
		
		public function get ws():WebService
		{
			return _ws;
		}
		
		public function SpotmeLocations(ipAddr:String,username:String = '',password:String = '',clusterName:String = "country") //extends WSDLService
		{
			//.super(ipAddr,username,password);
			this.clusterName = clusterName;
			_ip = ipAddr;
			_username = username;
			_password = password;
			
			_ws = new WebService();
			
			ws.wsdl = "http://"+ipAddr+"/spotme2-spotme2/GenericInterfaceAgentBean?wsdl";
            //trace(ws.wsdl);
            ws.endpointURI = "http://"+ipAddr+"/spotme2-spotme2/GenericInterfaceAgentBean";
            //
            ws.addEventListener("fault", faultHandler);
            ws.loadWSDL();
            ws.endpointURI = "http://"+ipAddr+"/spotme2-spotme2/GenericInterfaceAgentBean";
            //
            ws.sessionLogin(username,password);
            ws.sessionLogin.addEventListener("result", loginTokenHandler);
			
		}
		
		public function login():void
		{
			ws.sessionLogin(_username,_password);
            ws.sessionLogin.addEventListener("result", loginTokenHandler);
		}
		
		private function loginTokenHandler(event:ResultEvent):void
        {
        	if(event.result)
        	{
        		_token = event.result.toString();        		
        		//trace(_token);
        		ws.getPropMapbyOid.addEventListener("result", advloc_areaHandler);
        		ws.getPropMapbyOid("advloc_area",_token);
        		//ws.getPaxConnections.addEventListener("result", wallResultHandler);
        		//ws.getPaxConnections(token);
        		
        	}else
        	{
        		Alert.show('SpotmeLocations: Could not get auth token.');
        	}
        }
        
        private var _locations:Array = new Array();
        public function get locations():Array
        {
        	return _locations;
        }
        public function IsLocation(id:Object):Object
        {
        	for (var i:String in _locations) 
        	{
        		if(_locations[i]['id'] == id || _locations[i]['title'] == id)
        		{
        			return i;
        		}
        	}
        	return false;
        }
        private var _clusters:int = 0;
        public function get clusters():int{
        	return _clusters;
        }
        private function advloc_areaHandler(event:ResultEvent):void{
        	//trace('location handler',event.token[0],event.message,"\nHeaders-",event.headers,event.result);
        	_locations = new Array();
        	for (var p:String in event.result) {
        		//trace(p,event.result[p]);
        		//var lcns:Array = event.result[p].toString().split(",");        		
        		if(event.result[p][1] == "CONNECTIONWALL")
        		{
        			//trace(event.result[p][0]);
        			//_locations.push({id:event.result[p][0],title:"", x:"",y:""});
        			_locations[event.result[p][0]] = {id:event.result[p][0],title:"", x:0,y:0,theta:Math.PI/2,dx:0,dy:0,X:0,Y:0,count:0,dist:1,steps:1};
        			_clusters++;
        		}
        	}
        	trace('num locations/clusters',clusters,_locations.length);
        	
        	ws.getPropMapbyOid.removeEventListener("result", advloc_areaHandler);
        	ws.getPropMapbyOid.addEventListener("result", advloc_titleHandler);
        	ws.getPropMapbyOid("advloc_title",_token);
        	        	
        }
        
        private function advloc_titleHandler(event:ResultEvent):void{
        	//trace('advloc_titleHandler handler',event.token[0],event.message,"\nHeaders-",event.headers,event.result);
        	//_locations = new Array();
        	for (var p:String in event.result) {
        		//trace(p,event.result[p]);
        		//var lcns:Array = event.result[p].toString().split(",");
        		if(_locations[event.result[p][0]])
        		{
        			_locations[event.result[p][0]]['title'] = event.result[p][1];
        		}
        	}
        	
        	ws.getPropMapbyOid.removeEventListener("result", advloc_titleHandler);
        	ws.getPropMapbyOid.addEventListener("result", advloc_yposHandler);
        	ws.getPropMapbyOid("advloc_ypos",_token);
        	
        	
        	
        }
        private function advloc_yposHandler(event:ResultEvent):void{
        	//trace('advloc_yposHandler handler',event.token[0],event.message,"\nHeaders-",event.headers,event.result);
        	for (var p:String in event.result) {
        		//trace(p,event.result[p]);
        		//var lcns:Array = event.result[p].split(",");
        		if(_locations[event.result[p][0]])
        		{
        			_locations[event.result[p][0]]['x'] = new Number(event.result[p][1]);
        		}
        	}
        	
        	ws.getPropMapbyOid.removeEventListener("result", advloc_yposHandler);
        	ws.getPropMapbyOid.addEventListener("result", advloc_xposHandler);
        	ws.getPropMapbyOid("advloc_xpos",_token);
        	
        }
        public var clusterName:String = 'country';
        private function advloc_xposHandler(event:ResultEvent):void{
        	//trace('advloc_xposHandler handler',event.token[0],event.message,"\nHeaders-",event.headers,event.result);
        	for (var p:String in event.result) {
        		//trace(p,event.result[p]);
        		if(_locations[event.result[p][0]])
        		{
        			_locations[event.result[p][0]]['y'] = new Number(event.result[p][1]);
        		}
        	}
        	
			//trace('locations loaded',_locations.length);
        	for (var l:String in _locations) {
        		trace(l,_locations[l],_locations[l]['title'],_locations[l]['x'],_locations[l]['y']);
        		
        	}
        	
        	ws.getPropMapbyOid.removeEventListener("result", advloc_xposHandler);
        	ws.getPropMapbyOid.addEventListener("result", countryHandler);
        	trace('getting clusters:',clusterName);
        	ws.getPropMapbyOid(clusterName,_token);
        }
        /**
        * Assoc Array [Event Person ID]->location object{title,x,y}
        */
        private var _countryMap:Object;
        private var radius:Number = 40;
        public function getLoc(c:String):Object
        {
        	return _countryMap[c];
        	
        	if(_countryMap[c])
        	{
        		/*
        		if(0)//locations[_countryMap[c].id].title == 'France')
        		{
        			trace(locations[_countryMap[c].id].title,locations[_countryMap[c].id].steps,locations[_countryMap[c].id].dist,locations[_countryMap[c].id].count,''
        				,Math.round(locations[_countryMap[c].id].dx),Math.round(locations[_countryMap[c].id].dy)
        				,Math.round(locations[_countryMap[c].id].X),Math.round(locations[_countryMap[c].id].Y)
        				,Math.round(locations[_countryMap[c].id].theta));
        		}
        		if(locations[_countryMap[c].id].count != 0)
	        	{
	        		if(locations[_countryMap[c].id].steps++ >= locations[_countryMap[c].id].dist)//
	        		{
	        			locations[_countryMap[c].id].steps = 1;
	        			if(locations[_countryMap[c].id].count++ % 2 == 0)
	        			{
	        				locations[_countryMap[c].id].dist++;
	        			}
	        			locations[_countryMap[c].id].Y = radius*Math.sin(locations[_countryMap[c].id].theta);
		        		locations[_countryMap[c].id].X = radius*Math.cos(locations[_countryMap[c].id].theta);
		        		locations[_countryMap[c].id].theta += Math.PI/2;
	        		}
		        }else
		        {
		        	//start at the origin!
		        	locations[_countryMap[c].id].count++;
		        }
        		locations[_countryMap[c].id].dx += locations[_countryMap[c].id].X;//*radius;
        		locations[_countryMap[c].id].dy += locations[_countryMap[c].id].Y;//*radius;
        		*/
        		//we need to create a new object since we are itterating through _countryMap
        		var loc:Object = {id:locations[_countryMap[c].id].id,title:_countryMap[c].title, x:0,y:0};
        		loc.x = locations[_countryMap[c].id].x + Math.round(locations[_countryMap[c].id].dx);
        		loc.y = locations[_countryMap[c].id].y + Math.round(locations[_countryMap[c].id].dy);
        		//trace(loc.title+','+c+','+loc.x+','+loc.y);
        		return loc;
        		//countryMap[c] = {title:_countryMap[c].title, x:0,y:0};
        		//countryMap[c].x = locations[_countryMap[c].id].x + Math.round(locations[_countryMap[c].id].dx);
        		//countryMap[c].y = locations[_countryMap[c].id].y + Math.round(locations[_countryMap[c].id].dy);
        		//trace(countryMap[c].title+','+c+','+countryMap[c].x+','+countryMap[c].y);
        	}
        	return null;
        }
        public var countryMap:Object = new Object();

        private function countryHandler(event:ResultEvent):void{
        	_countryMap = new Object();
        	//trace('country handler',event.result);
        	for (var p:String in event.result) {
        		var i:Object = IsLocation(event.result[p][1]);
        		if(i)
        		{
        			//trace(p,event.result[p]);
        			_countryMap[event.result[p][0]] = _locations[i];
        		}
        	}

			return;
			
        }
        
        private function faultHandler(event:FaultEvent):void {
                Alert.show("SpotmeLocations: Cannot connect");
                //timer.start();
        }

	}
}